﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using TvTipper.Entities;
using TvTipper.Core;
using TvTipper.Api;

namespace TvTipper.Controls
{
    public partial class TvProgramInfoPanel : BaseInfoPanel
    {
        public TvProgramInfoPanel()
        {
            InitializeComponent();
        }

        protected override void Clear()
        {
            m_pic.Image = null;
            ClearAllTextFields();
        }

        protected override void LoadNewEntity(Entity entity)
        {
            var program = (TvProgram)entity;

            m_bs.DataSource = program;

            //info
            if (!string.IsNullOrEmpty(program.Description) && program.Description.StartsWith("/m/"))
            {
                m_info.Visible = false;
                m_infoWeb.Visible = true;
                var infoUri = string.Format("http://img.freebase.com/api/trans/raw/{0}", program.Description);
                m_infoWeb.Navigate(infoUri);
            }
            else
            {
                m_infoWeb.Visible = false;
                m_info.Visible = true;
            }

            // image
            if (!string.IsNullOrEmpty(program.ImageUrl))
            {
                var finalUri = string.Format("https://usercontent.googleapis.com/freebase/v1/image/{0}?maxwidth={1}&maxheight={2}",
                    program.Id,
                    m_pic.Width,
                    m_pic.Height);
                m_pic.Image = ImageManager.Instance.getImage(finalUri);
            }
            else
            {
                var finalUri = string.Format("https://usercontent.googleapis.com/freebase/v1/image/06l46n?maxwidth={0}&maxheight={1}",
                    m_pic.Width,
                    m_pic.Height);
                m_pic.Image = ImageManager.Instance.getImage(finalUri);
            }

            // show generes
            var generes = Services.EntityManager.GetLookup(LookupType.Genere);
            var labels = generes.
                Where(g => program.Generes.Contains(g.Id)).
                Select(g => g.Name);
            m_genres.Text = String.Join(" | ", labels);
            
            // show cast
            var distinctRoles = program.Cast.Select(c => c.RoleId).
                Distinct();
            var roles = Services.EntityManager.GetLookup(LookupType.Role);

            m_cast.Text = "";
            foreach (var roleId in distinctRoles)
            {
                var label = roles.Where(r => roleId == r.Id).First().Name;
                var names = program.Cast.Where(c => c.RoleId == roleId).Select(c => c.PersonName);

                var roleLine = string.Format("{0}(s): {1}\n", label, string.Join(", ", names));
                m_cast.Text += roleLine;
            }
        }
    }
}
